import { useState } from 'react'
import {
  Modal,
  Form,
  Input,
  InputNumber,
  Message,
  Alert,
  Space,
  Button,
  Typography,
} from '@arco-design/web-react'
import { IconCopy, IconCheck } from '@arco-design/web-react/icon'
import { createRegistrationToken } from '@/api/node'
import type { NodeRegistrationToken } from '@/types'
import './index.css'

const FormItem = Form.Item
const { Paragraph, Text } = Typography

interface NodeRegistrationTokenModalProps {
  visible: boolean
  onCancel: () => void
  onSuccess: () => void
}

export default function NodeRegistrationTokenModal({
  visible,
  onCancel,
  onSuccess,
}: NodeRegistrationTokenModalProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [token, setToken] = useState<NodeRegistrationToken | null>(null)
  const [copiedToken, setCopiedToken] = useState(false)
  const [copiedCommand, setCopiedCommand] = useState(false)

  const handleSubmit = async () => {
    try {
      const values = await form.validate()
      setLoading(true)

      const tokenData = await createRegistrationToken(values)
      setToken(tokenData)
      Message.success('注册令牌创建成功')
    } catch (error) {
      console.error('Failed to create registration token:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    form.resetFields()
    setToken(null)
    setCopiedToken(false)
    setCopiedCommand(false)
    onCancel()
  }

  const handleConfirm = () => {
    form.resetFields()
    setToken(null)
    setCopiedToken(false)
    setCopiedCommand(false)
    onSuccess()
  }

  const copyToClipboard = async (text: string, type: 'token' | 'command') => {
    try {
      await navigator.clipboard.writeText(text)
      if (type === 'token') {
        setCopiedToken(true)
        setTimeout(() => setCopiedToken(false), 2000)
      } else {
        setCopiedCommand(true)
        setTimeout(() => setCopiedCommand(false), 2000)
      }
      Message.success('已复制到剪贴板')
    } catch (error) {
      Message.error('复制失败')
    }
  }

  return (
    <Modal
      title={token ? '注册令牌已生成' : '生成节点注册令牌'}
      visible={visible}
      onCancel={handleClose}
      onOk={token ? handleConfirm : handleSubmit}
      confirmLoading={loading}
      autoFocus={false}
      focusLock={true}
      okText={token ? '完成' : '生成'}
      cancelText="取消"
      maskClosable={false}
      escToExit={!token}
    >
      {!token ? (
        <Form form={form} layout="vertical" autoComplete="off">
          <FormItem
            label="令牌名称"
            field="name"
            rules={[
              { required: true, message: '请输入令牌名称' },
              { minLength: 2, message: '名称至少2个字符' },
              { maxLength: 50, message: '名称最多50个字符' },
            ]}
          >
            <Input placeholder="例如：生产环境节点" />
          </FormItem>

          <FormItem
            label="描述"
            field="description"
            rules={[{ maxLength: 200, message: '描述最多200个字符' }]}
          >
            <Input.TextArea
              placeholder="请输入令牌用途描述"
              rows={3}
              showWordLimit
              maxLength={200}
            />
          </FormItem>

          <FormItem
            label="有效期（小时）"
            field="expiresInHours"
            rules={[
              { required: true, message: '请输入有效期' },
              {
                type: 'number',
                min: 1,
                max: 8760,
                message: '有效期必须在 1-8760 小时之间',
              },
            ]}
            initialValue={24}
          >
            <InputNumber
              placeholder="24"
              min={1}
              max={8760}
              style={{ width: '100%' }}
            />
          </FormItem>

          <FormItem
            label="最大使用次数"
            field="maxUsageCount"
            rules={[
              { required: true, message: '请输入最大使用次数' },
              {
                type: 'number',
                min: 1,
                max: 100,
                message: '使用次数必须在 1-100 之间',
              },
            ]}
            initialValue={1}
          >
            <InputNumber
              placeholder="1"
              min={1}
              max={100}
              style={{ width: '100%' }}
            />
          </FormItem>

          <Alert
            type="info"
            content="令牌生成后，请妥善保管。令牌将在达到使用次数或过期后失效。"
          />
        </Form>
      ) : (
        <div className="token-result">
          <Alert
            type="success"
            content="注册令牌已成功生成，请复制以下信息用于节点注册。"
            style={{ marginBottom: 16 }}
          />

          <div className="token-info">
            <div className="token-section">
              <div className="token-label">
                <Text bold>令牌名称：</Text>
                <Text>{token.name}</Text>
              </div>
              {token.description && (
                <div className="token-label">
                  <Text bold>描述：</Text>
                  <Text type="secondary">{token.description}</Text>
                </div>
              )}
            </div>

            <div className="token-section">
              <Space direction="vertical" style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography.Text bold>注册令牌：</Typography.Text>
                  <Button
                    type="text"
                    size="small"
                    icon={copiedToken ? <IconCheck /> : <IconCopy />}
                    onClick={() => copyToClipboard(token.token, 'token')}
                  >
                    {copiedToken ? '已复制' : '复制'}
                  </Button>
                </div>
                <Paragraph
                  code
                  copyable
                  style={{
                    fontSize: 12,
                    padding: 12,
                    background: '#f7f8fa',
                    borderRadius: 4,
                    margin: 0,
                    wordBreak: 'break-all',
                  }}
                >
                  {token.token}
                </Paragraph>
              </Space>
            </div>

            {token.registrationCommand && (
              <div className="token-section">
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography.Text bold>注册命令：</Typography.Text>
                    <Button
                      type="text"
                      size="small"
                      icon={copiedCommand ? <IconCheck /> : <IconCopy />}
                      onClick={() =>
                        copyToClipboard(token.registrationCommand!, 'command')
                      }
                    >
                      {copiedCommand ? '已复制' : '复制'}
                    </Button>
                  </div>
                  <Paragraph
                    code
                    style={{
                      fontSize: 12,
                      padding: 12,
                      background: '#1d1d1d',
                      color: '#d4d4d4',
                      borderRadius: 4,
                      margin: 0,
                      wordBreak: 'break-all',
                      fontFamily: 'Consolas, Monaco, monospace',
                    }}
                  >
                    {token.registrationCommand}
                  </Paragraph>
                </Space>
              </div>
            )}

            <div className="token-section">
              <Space direction="vertical" size="small">
                <div>
                  <Text type="secondary">有效期至：</Text>
                  <Text>{new Date(token.expiresAt).toLocaleString()}</Text>
                </div>
                <div>
                  <Text type="secondary">最大使用次数：</Text>
                  <Text>{token.maxUsageCount}</Text>
                </div>
                <div>
                  <Text type="secondary">已使用次数：</Text>
                  <Text>{token.usedCount}</Text>
                </div>
              </Space>
            </div>
          </div>

          <Alert
            type="warning"
            content="请妥善保管此令牌，关闭窗口后将无法再次查看完整令牌信息。"
            style={{ marginTop: 16 }}
          />
        </div>
      )}
    </Modal>
  )
}
